package com.navi.loaddata.job;

import com.navi.loaddata.core.etlException.ETLException;
import com.navi.loaddata.core.job.QuartzManage;
import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.loadService.IEtlConfServices;
import com.navi.loaddata.loadService.impl.opeEqptData.LoadEqptDataService;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * LoadOpeData
 *
 * @author Matthew
 * @date 2018-05-04
 */
public class LoadEqptData implements Job {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private IEtlConfServices etlConfServices;

  @Autowired
  private QuartzManage quartzManage;

  @Autowired
  private LoadEqptDataService loadEqptDataService;
  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    JobDetail jobDetail = jobExecutionContext.getJobDetail();
    JobDataMap jobDataMap = jobDetail.getJobDataMap();
    EtlConfD etlConfD = (EtlConfD) jobDataMap.get("etlConf");
    etlConfD = etlConfServices.getNewConf(etlConfD);
    if(null==etlConfD) {
      logger.error("找不到该JOB。");
      return;
    }

    if ("N".equals(etlConfD.getRunFlg())) {
      etlConfD = etlConfServices.beginJob(etlConfD);
      if (StringUtils.isEmpty(etlConfD.getQueryMinute())) {
        return;
      }
      startETL(etlConfD);
    } else {
      logger.info("Job {}-{} is running.", etlConfD.getJobGroupName(), quartzManage.getRealJobName(etlConfD));
    }
  }

  private void startETL(EtlConfD etlConfD) {
    int countSize = 0;
    try {
      countSize = loadEqptDataService.loadEqptDataMain(etlConfD);
      etlConfD.setCountSize(countSize);
      etlConfServices.endJob(etlConfD);
      etlConfServices.addHis(etlConfD, null);
    } catch (ETLException e) {
      logger.info("Job {} [{}]-[{}] FAIL TO SYNCHRONIZE.", etlConfD.getProjectName() + etlConfD.getJobGroupName() + etlConfD.getJobName(), etlConfD.getRunStartTimestamp(), etlConfD.getRunEndTimestamp());
      etlConfD.setCountSize(0);
      etlConfServices.endJob(etlConfD);
      etlConfServices.addHis(etlConfD,e.getMessage());
    }
  }
}
